const { getUserLinksArtWork } = require("../../utils/request");
const config = require("../../utils/config");

Page({
  data: {
    artworks: [],  // 艺术作品列表数据
    pageNum: 1, // 当前页数
    pageSize: 10, // 每页显示的条数
    isLoading: false, // 是否正在加载数据
    hasMore: true, // 是否还有更多数据
    hasLoadedData: false, // 数据是否已经加载过
  },

  onLoad() {
    console.log("onLoad()方法");
    this.loadArtworks();
  },

  onShow() {
    // 只在数据没有加载过的情况下进行加载
    if (!this.data.hasLoadedData) {
      console.log("onShow()方法");
      this.refreshArtworks();
    }
  },

  onReachBottom() {
    // 当页面滚动到底部时触发
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadMoreArtworks();
    }
  },

  async loadArtworks() {
    this.setData({ 
      isLoading: true,
      hasLoadedData: true,  // 标记数据已加载
     });
    const { pageNum, pageSize } = this.data;

    getUserLinksArtWork({ pageNum, pageSize }).then(res => {
      if (res.code === '00000' && res.data && res.data.list) {
        const updatedArtworks = res.data.list.map((artwork) => ({
          ...artwork,
          primaryImageSmallUrl: `${config.ImageURL}${artwork.primaryImageSmallUrl}`,
        }));
        this.setData({
          artworks: [...this.data.artworks, ...updatedArtworks],
          hasMore: updatedArtworks.length >= pageSize,
        });
        console.log("获取到的艺术作品数据：" + updatedArtworks);
      } else {
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      }
    }).catch(err => {
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ 
        isLoading: false,
        hasLoadedData: false,
       });
    });
  },

  async loadMoreArtworks() {
    const { pageNum } = this.data;
    this.setData({ pageNum: pageNum + 1 });
    this.loadArtworks();
  },

  async refreshArtworks() {
    // 当页面返回时，重置数据并重新查询
    this.setData({
      pageNum: 1,
      artworks: [],
      leftColumn: [],
      rightColumn: [],
      hasMore: true,
    });
    this.loadArtworks();
  },
});
